
import Foundation
import Flutter
import UIKit
import StoreKit
import AppTrackingTransparency
import FBSDKCoreKit
import AdSupport
public class CommomPlugin {

    var mMessageChannel:FlutterMethodChannel
    var mFlutterCV:FlutterViewController

    var application: UIApplication
    var launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    var result:FlutterResult?


    init(controller :FlutterViewController,application: UIApplication,launchOptions: [UIApplication.LaunchOptionsKey : Any]? ){
        mFlutterCV=controller
        self.application=application
        self.launchOptions = launchOptions
        mMessageChannel = FlutterMethodChannel(name: "CommomPlugin", binaryMessenger: controller.binaryMessenger)
        mMessageChannel.setMethodCallHandler(self.handle)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

        if call.method == "goToRate" {
            SKStoreReviewController.requestReview()
//        } else if call.method=="toNearbyBanks"{
//            UIApplication.shared.keyWindow?.rootViewController?.present(NearbyBankPage(), animated: true, completion:nil)
        } else if call.method=="openATT"{
            self.openATT(call, result: result)
//        } else if call.method=="initAdjust"{
//            self.initAdjust(call, result: result)
        } else if call.method=="initFB"{
            self.initFB(call, result: result)
//        } else if call.method=="GetFacePath"{
//            self.GetFacePath(call, result: result)
        }else {
            result(FlutterMethodNotImplemented)
        }
    }
//
//    public func initAdjust(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
////         let yourAppToken = (call.arguments as? NSDictionary)?.value(forKey: "YourAppToken") as? String
////         let environment = ADJEnvironmentProduction as String
////         let adjustConfig = ADJConfig(
////            appToken: yourAppToken ?? "",
////             environment: environment)
//////          adjustConfig?.urlStrategy=ADJUrlStrategyIndia
//////         adjustConfig?.logLevel = ADJLogLevelVerbose
////         Adjust.appDidLaunch(adjustConfig)
//        result(true)
//    }


    public func initFB(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let appID = (call.arguments as? NSDictionary)?.value(forKey: "appID") as! String
        let appName = (call.arguments as? NSDictionary)?.value(forKey: "appName") as! String
        let clientToken = (call.arguments as? NSDictionary)?.value(forKey: "clientToken") as! String
        let urlScheme = (call.arguments as? NSDictionary)?.value(forKey: "urlScheme") as! String
        initializeFacebookSDK(appID: appID, appName: appName, clientToken: clientToken, urlScheme: urlScheme)
        result(true)
    }

    func initializeFacebookSDK(appID: String,appName:String,clientToken:String,urlScheme:String) {
        // 设置 Facebook SDK 的配置项
        Settings.shared.appID = appID
        Settings.shared.displayName = appName
        Settings.shared.clientToken = clientToken
        Settings.shared.appURLSchemeSuffix = urlScheme
        Settings.shared.isAutoLogAppEventsEnabled=true

        // 修改 Info.plist 文件的内容
//        if let infoPlistPath = Bundle.main.path(forResource: "Info", ofType: "plist"),
//        var infoDict = NSMutableDictionary(contentsOfFile: infoPlistPath) {
//            infoDict["FacebookAppID"] = appID
//            infoDict["FacebookDisplayName"] = appName
//            infoDict["FacebookClientToken"] = clientToken
//
//            if var urlTypes = infoDict["CFBundleURLTypes"] as? [[String: Any]], !urlTypes.isEmpty,
//            var urlType = urlTypes.first, var urlSchemes = urlType["CFBundleURLSchemes"] as? [String], !urlSchemes.isEmpty {
//            urlSchemes[0] = urlScheme
//            urlType["CFBundleURLSchemes"] = urlSchemes
//            urlTypes[0] = urlType
//            infoDict["CFBundleURLTypes"] = urlTypes
//        }
//
//            if infoDict.write(toFile: infoPlistPath, atomically: true) {
//            ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
//        }
//        }

        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    }


    
//    public func GetFacePath(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
//        let language = (call.arguments as? NSDictionary)?.value(forKey: "language") as? String?
//        let twoVC = FacePage(nibName:"FacePage", bundle: nil)
////             if(language=="en"){
////                 twoVC.language=India
////             }else{
////                 twoVC.language = Indonesia
////             }
//        twoVC.callBackParamter={(map)->Void in
//            let image = map["image"]as! UIImage
//            image.compress()
//            let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
//            let fileURL = documentsDirectoryURL.appendingPathComponent( "fileImage.png")
//            do {
//                try image.pngData()?.write(to: fileURL)
//                result(fileURL.path)
//            } catch {
//            }
//        }
//        UIApplication.shared.keyWindow?.rootViewController?.present(twoVC, animated: true, completion:nil)
//    }
    public func openATT(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

        if #available(iOS 14.0, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
                    switch status {
                case .denied:
                result(false)
                case .authorized:
                Settings.shared.isAdvertiserTrackingEnabled = true
                result(true)
                case .notDetermined:
                ATTrackingManager.requestTrackingAuthorization { st in
                        switch st {
                    case .authorized:
                    result(true)
                    Settings.shared.isAdvertiserTrackingEnabled = true
                    case .notDetermined:
                    result(true)
                    default:
                    result(false)
                    break
                }
                }

                default:
                break
            }
        } else {
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                result(true)
            } else {
                result(true)
            }
        }
    }
}
